package com.dunmin.concurrency.atomic;

import com.dunmin.concurrency.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * Created by Administrator on 2018/4/24.
 */
@Slf4j
@ThreadSafe
public class AtomicExample3 {


    // 请求总数
    public static int clientTotal = 5000;
    // 同时并发执行的线程数
    public static int threadTotal = 500;
    public static LongAdder count = new LongAdder();


    // 线程不安全方法
    private static void add() {
        // 先增加再获取值
        //count.incrementAndGet();
        // 先取值再增加操作
        count.increment();
    }

    public static void main(String[] args) throws InterruptedException {
        // 定义
        ExecutorService excutorService = Executors.newCachedThreadPool();
        // 信号量 允许并发的数目
        final Semaphore semaphore = new Semaphore(threadTotal);
        // 所有请求结束之后计算结果
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++){
            excutorService.execute(() ->{
                try{
                    // 引入信号量,只有当信号量返回值后 add()才会执行
                    semaphore.acquire();
                    add();
                    semaphore.release();
                }
                catch(InterruptedException e){
                    log.error("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        // 保证countDownLatch减为0,就是所有的进程都执行完
        countDownLatch.await();
        // 关闭线程池
        excutorService.shutdown();
        log.info("count:{}",count);

    }
}